package com.zhaogang.transactionManagerDemo.service.impl;

import java.util.Date;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhaogang.transactionManagerDemo.entity.SystemLog;
import com.zhaogang.transactionManagerDemo.mapper.SystemLogMapper;
import com.zhaogang.transactionManagerDemo.service.SystemLogService;

@Service
public class SystemLogServiceImpl implements SystemLogService {

	private static ObjectMapper objectMapper = new ObjectMapper();
	private static Logger logger = LoggerFactory.getLogger(SystemLogServiceImpl.class);
	
	@Autowired
	private SystemLogMapper logMapper;
	
	@Override
//	@Transactional(propagation = Propagation.REQUIRED)
	@Transactional(propagation = Propagation.REQUIRES_NEW)
//	@Transactional(propagation = Propagation.NESTED)
	public SystemLog addLog(String topic, String tableName, Object old, Object now) {
		SystemLog log_prev = new SystemLog();
		log_prev.setTopic("");
		log_prev.setTableName("");
		log_prev.setJsonPrev("");
		log_prev.setJson("print log before");
		Date lastModifiedTime = new Date();
		log_prev.setLastModifiedTime(lastModifiedTime);
		logMapper.insert(log_prev);
		
		SystemLog log = new SystemLog();
		log.setTopic(StringUtils.isBlank(topic)?"":topic);
		log.setTableName(StringUtils.isBlank(tableName)?"":tableName);
		try {
			log.setJsonPrev(Objects.equals(old, null) ? "" : objectMapper.writeValueAsString(old));
			log.setJson(Objects.equals(now, null) ? "" : objectMapper.writeValueAsString(now));
		} catch (JsonProcessingException e) {
			logger.info(e.getMessage(),e);
		}
		log.setLastModifiedTime(lastModifiedTime);
		logMapper.insert(log);
		
		log_prev.setJson("print log after");
		logMapper.insert(log_prev);		
		
		return log;
	}

}
